﻿var baseTreeUrl = CPWebRootPath + "/api/TreeEngine/GetTreeData";                    //获取树形列表url
var carArray;                           //获取车辆信息列表数据
var totalCarCount;                      //车辆总数量
var getCarDeviceCount = 0;              //获取车载设备信息时，每次请求执行后自增1，用于和车辆总数量进行比较
var inum = 0;                           //记录调整视野代码执行的次数
var timeArr, temArr, humArr = [];       //历史数据集合，用于给echart提供数据。时间、温度、湿度
var points;                             //地图点
var allpoints = [];                     //获取到的所有点，用于调整百度地图的视野
var selectpoints = [];                  //获取车辆的第一个传感器的经纬度信息，用于点击左侧车牌号定位车辆
var mapview;                            //地图视野
var mapZoom;                            //地图显示级别
var covarr;                             //将每个车辆的覆盖物信息放到隐藏域中

// 百度地图API功能
var map = new BMap.Map("allmap", { enableMapClick: false });  //创建地图实例
var point = new BMap.Point(116.404, 39.915);
//创建点坐标
map.centerAndZoom(point, 6);                                  //初始化地图，设置中心点坐标和地图级别
map.enableScrollWheelZoom(true);                              //允许鼠标滚动轮缩放地图
var myGeo = new BMap.Geocoder();                              //创建地址解析器实例

$(function () {
    $("#allmap").height($(document).height() - 70);
    $("#menu-1").height($(document).height() - 70);
    $("#w-map-silder1").height($(document).height() - 70);
    showrealinfo();
});


$("#checkCar").click(function () {
    //$("#accordion").html("");
    //map.clearOverlays();
    var carNumberCheck = $("#carNumberCheck").val();
    showrealinfo(carNumberCheck);

})

//显示所有车辆的基本信息、实时信息、点击车牌号定位车辆
function showrealinfo(carNumberOption) {
    var inputObj = new Object();
    inputObj.TreeCode = "Tree201811051442280001";
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    if (carNumberOption != null) {
        baseTreeUrl += "?CarNumber=" + carNumberOption;
    }
    $.ajax({
        type: "POST",
        url: baseTreeUrl,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        async: true,
        success: function (result) {  //回调函数，result，返回值  
            $("#roomshow").css('display', 'block');
            if (result.Result == true) {
                carArray = result.DataCol;
                if (carArray != null) {
                    $("#accordion").html("");
                    var thisCount = 0;//用于记录目前读取的是第几辆车
                    $(carArray).each(function (realindex, object) {
                        //获取车辆基本信息
                        var CarInfo = $.parseJSON(object.DataRowJSON);
                        //获取此车运输的订单
                        var ordersArray = object.items;
                        var orderCount = ordersArray.length;
                        var orderCountSend = 0;                                //已配送订单数量
                        var orderCountNotSend = 0;                             //未配送订单数量
                        var chickenCountTotal = 0;                             //此车运输所有雏鸡数量
                        var chickenCountSend = 0;                              //已配送雏鸡数量
                        var chickenCountNotSend = 0;                           //未配送雏鸡数量
                        var firstOrder = ordersArray[0];                       //第一个订单
                        var lastOrder = ordersArray[ordersArray.length - 1];   //最后一个订单
                        var lastOrderAddress = $.parseJSON(lastOrder.DataRowJSON);
                        var startAddress = $.parseJSON(firstOrder.DataRowJSON).BaseName;    //始发地：第一个订单的基地名称
                        var destination = lastOrderAddress.CustomerState + lastOrderAddress.CustomerCity + lastOrderAddress.CustomerDistrict + lastOrderAddress.CustomerAddress;                    //运输终点：最后一个订单的地址
                        //计算未配送、已配送订单数量、雏鸡数量
                        $(ordersArray).each(function (orderindex, orderObject) {
                            var orderInfo = $.parseJSON(orderObject.DataRowJSON);
                            var carDeliveryStatus = orderInfo.CarDeliveryStatus;
                            chickenCountTotal += Number(orderInfo.OrderChickCountInCar);
                            if (carDeliveryStatus == 2 || carDeliveryStatus == 3) {
                                orderCountSend++;
                                chickenCountSend += Number(orderInfo.OrderChickCountInCar);
                            }
                            else {
                                orderCountNotSend++;
                                chickenCountNotSend += Number(orderInfo.OrderChickCountInCar);
                            }

                        })

                        //拼接左侧浮动框内容
                        var LeftHtml = '<div class="panel">'
                            + '<div class="panel-heading">'
                            + '    <h4 class="panel-title">'
                            + '        <a data-toggle="collapse" data-parent="#accordion" href="#collapse' + realindex + '" onclick="showCar(' + realindex + ');">'
                            //+ '        <a data-toggle="collapse" data-parent="#accordion" href="#collapse' + index + '" onclick="hideInfo();">'
                            + '            <div class="pull-left w-silder-titll">'
                            + '                <p class="pull-left cor-blue"><i class="iconfont  cor-blue">&#xe616;</i> <b>' + CarInfo.CarNumber + '</b></p>'
                            + '            </div>'
                            + '            <div class="pull-right w-silder-titrr">'
                            //+ '                <p class="pull-left"><i class="iconfont text-success"><b>&#xe603;</b></i><em class="font-12">正常</em></p>'
                            + '            </div>'
                            + '        </a> '
                            + '    </h4>'
                            + '</div>'
                            + '<div id="collapse' + realindex + '" class="panel-collapse collapse">'
                            + '    <div class="panel-body">'
                            + '        <div class="w-detail">'
                            + '            <div class="w-detail-content"><i class="iconfont w-icon">&#xe60d;</i> ' + CarInfo.MainDriverName + ' <em>' + CarInfo.MainDriverTel + '</em></div>'
                            + '            <div class="w-detail-content"><i class="iconfont w-icon">&#xe601;</i><em id="address' + realindex + '">' + destination + '</em></div>'
                            + '            <div class="w-detail-content">'
                            + '                <div class="w-detail-content-left">订单量</div>'
                            + '                <div class="w-detail-content-left-center">(配送中/已配送)</div>'
                            + '            </div>'
                            + '            <div class="w-detail-content">'
                            + '                <div class="w-detail-content-left">' + '<em id="orderCount' + realindex + '"></em>' + orderCount + '个</div>'
                            + '                <div class="w-detail-content-left-center">(' + '<em id="notsendOrderCount' + realindex + '"></em>' + orderCountNotSend + '个/' + '<em id="sendOrderCount' + realindex + '"></em>' + orderCountSend + '个)</div>'
                            + '            </div>'
                            + '            <div class="w-detail-content">'
                            + '                <div class="w-detail-content-left">' + '<em id="chickenCountInCar' + realindex + '"></em>' + chickenCountTotal + '只</div>'
                            + '                <div class="w-detail-content-left-center">(' + '<em id="notsendCount' + realindex + '"></em>' + chickenCountNotSend + '只/' + '<em id="sendCount' + realindex + '"></em>' + chickenCountSend+ '只)</div>'
                            + '            </div>'
                            + '        </div>'
                            + '        <div class="w-detail">'
                            + '            <div class="w-detail-content">'
                            + '                <div class="w-detail-content-btn"><input type="button" name="" value="环境" class="content-btn btn-color1" onclick="showCar(' + realindex + ');"></div>'
                            + '                <div class="w-detail-content-btn"><input type="button" name="" value="订单" class="content-btn btn-color2" onclick="showOrder(\'' + CarInfo.TaskId + '\',\'' + CarInfo.CarNumber + '\');"> </div>'
                            + '                <div class="w-detail-content-btn"><input type="button" name="" value="历史轨迹" class="content-btn btn-color3" onclick="showHistoryPath(\'' + CarInfo.CarNumber + '\',\''  + CarInfo.SensorId + '\',\'' + CarInfo.CarLeaveTime + '\',\'' + startAddress + '\',\'' + destination + '\');"></div>'
                            + '            </div>'
                            + '        </div>'
                            + '    </div>'
                            + '</div>'
                            + '</div>';
                        $("#accordion").append(LeftHtml);                       
                    });
                    totalCarCount = carArray.length;
                    console.log("车辆个数:" + totalCarCount)
                    //加载实时温湿度数据
                    InitCurrentData(carArray);                   
                }
                else {
                    alert("未查询到车辆信息！");
                }
            }
            else {
                alert("获取车辆信息时出错！");
            }
        },
        complete: function (x) {
        }
    });
}

//加载实时数据
function InitCurrentData(carInfos) {
    allpoints = new Array;
    $(carInfos).each(function (index, object) {
        //获取车辆基本信息
        var thisCarInfo = $.parseJSON(object.DataRowJSON);
        var snSensor = thisCarInfo.SensorId;
        var snGPS = thisCarInfo.GPSId;
        getDeviceInfo(index, snGPS, snSensor);
    })
  
    //定义一个定时器zoomInterval，当视野调整完成后，就不再定时执行a
    var zoomInterval = setInterval(function () {
        //需要定时执行的代码：根据所有点位置确定百度地图的视野         
        if (totalCarCount == getCarDeviceCount) {
            setZoom();
        }
        inum++;
        //当视野确定后，清空定时执行的代码
        if (inum > 1) {
            clearInterval(zoomInterval);
        };
    }, 1000);
    //setTimeout( setZoom,2000);
}


function getDeviceInfo(index, snGPS, snSensor) {
    //每次获取数据之前，将原有的覆盖物清空
    $("#covarr" + index).remove();
    //map.clearOverlays();
    var arrayOverlays = map.getOverlays();
    for (var i = 0; i < arrayOverlays.length; i++) {
        if (arrayOverlays[i].id == index) {
            map.removeOverlay(arrayOverlays[i]);
        }
    }
    //根据sn号获取实时数据
    $.ajax({
        type: "GET",
        //url: currentInfoUrl + "?GpsId=" + snGPS + "&SensorIds=" + snSensor,
        url: currentDataUrl + "?SN=" + snSensor,
        dataType: 'json',
        async: true,
        error: function (x, e) {
            alert("未查询到实时数据！");
        },
        success: function (result) {
            var json = result;
                var pntlist = json.datalist;//回调函数，result，返回值
                if (pntlist.length != 0) {
                    var senlist = pntlist[0].valuelist;       //获取的数据值
                    var unitlist = pntlist[0].fielddim;       //单位数组
                    var sensorfield = pntlist[0].sensorfield; //数据含义

                    var sensor = senlist[0].fieldvalue;;
                    points = new Array();
                    var lng, lat;        //传感器实时温湿度  
                    var temperature1, temperature2, humidity1, humidity2,speed;   
                    var unitTem, unitHum,unitSpeed;
                    temperature1 = sensor[0];
                    humidity1 = sensor[1];
                    temperature2 = sensor[2];
                    humidity2 = sensor[3];
                    lat= sensor[4];
                    lng = sensor[5];
                    speed = sensor[8];
                    unitTem = unitlist[0];
                    unitHum = unitlist[1];
                    unitSpeed = unitlist[8];
                    var temperatureArr = [];
                    var humidityArr = [];
                    var unitTemArr = [];
                    var unitHumArr = [];

                    //保存传感器的经纬度信息，用于：当点击左侧菜单的车牌号时，定位到相应车辆
                    var newpoint = new BMap.Point(lng, lat);
                    selectpoints[index] = newpoint;

                    points[0] = { "lng": lng, "lat": lat };
                    var thispoint = new BMap.Point(lng, lat);
                    myGeo.getLocation(thispoint, function (rs) {
                        var addComp = rs.addressComponents;
                        $("#address" + index).html(addComp.city + addComp.district + addComp.street + addComp.streetNumber);
                    });

                    //判断冷库温湿度是否正常     
                    //isNormal(htem, ltem, hhum, lhum, temperature, humidity, ptnidinfo, index);

                    var carInfo = $.parseJSON(carArray[index].DataRowJSON);
                    //获取此车运输的订单
                    var ordersArrayInCar = carArray[index].items;
                    var firstOrder = ordersArrayInCar[0];                               //第一个订单
                    var thelastOrder = ordersArrayInCar[ordersArrayInCar.length - 1];   //最后一个订单
                    var thelastOrderAddress = $.parseJSON(thelastOrder.DataRowJSON);
                    var startAddress = $.parseJSON(firstOrder.DataRowJSON).BaseName;    //始发地：第一个订单的基地名称
                    var destination = thelastOrderAddress.CustomerState + thelastOrderAddress.CustomerCity + thelastOrderAddress.CustomerDistrict + thelastOrderAddress.CustomerAddress;    //目的地：最后一个订单的地址                    
                    var cov = ' <div class="w-locon-two "> '
                        + '<div class="w-locon-twott">'
                        + '    <div class="twott-info">'
                        + '        <p>车牌号</p><p>' + carInfo.CarNumber + '</p>'
                        + '    </div>'
                        + '    <div class="twott-title"> '
                        + '        <p>始发地：' + startAddress + '</p><p>目的地：' + destination + '</p>'
                        + '    </div>'
                        + '</div>'
                        + '<div class="w-locon-value" id="w-locon-value' + index + '">'
                        + '    <ul class="w-jclk" id="sensorInfo' + index + '">'
                        + '        <li class="cor-green" id="temInfo' + index + '"> '
                        + '           <p> ' + temperature1 + unitTem + '</p> '
                        +'            <p><i class="iconfont  font-30 cor-green">&#xe605;</i></p> <p class="cor-gre font-12">温度</p></li > '
                        + '        <li class="cor-purple" id="humInfo' + index + '">'
                        + '           <p>' + humidity1 + unitHum + '</p>'
                        + '           <p><i class="iconfont  font-30 cor-purple">&#xe606;</i></p>  <p class="cor-gre font-12">湿度</p></li>'
                        + '        <li class="cor-yellow" id="speedInfo' + index + '">'
                        + '           <p>' + speed + unitSpeed + '</p>'
                        + '           <p><i class="iconfont  font-30 cor-purple">&#xe60f;</i></p>  <p class="cor-gre font-12">速度</p></li>'
                        + '    </ul>'
                        + '    <ul class="w-jclk" id="sensorInfo' + index + '">'
                        + '        <li class="cor-green" id="temInfo' + index + '"> '
                        + '           <p> ' + temperature2 + unitTem + '</p> '
                        + '            <p><i class="iconfont  font-30 cor-green">&#xe605;</i></p> <p class="cor-gre font-12">温度</p></li > '
                        + '        <li class="cor-purple" id="humInfo' + index + '">'
                        + '           <p>' + humidity2 + unitHum + '</p>'
                        + '           <p><i class="iconfont  font-30 cor-yellow">&#xe606;</i></p>  <p class="cor-gre font-12">湿度</p></li>'
                        + '        <li class="cor-yellow" id="speedInfo' + index + '">'
                        + '           <p>' + speed + unitSpeed + '</p>'
                        + '           <p><i class="iconfont  font-30 cor-yellow">&#xe60f;</i></p>  <p class="cor-gre font-12">速度</p></li>'
                        + '    </ul>'
                        + '</div>'
                    covarr = '<div id="covarr' + index + '" >' + cov + '</div>';
                    $("body").append(covarr);
                    //将得到的每个车辆的详细信息放到隐藏域中    
                    $("#covarr" + index).css("display", "none");                   

                    //地图铺点
                    label = new BMap.Label(cov, { offset: new BMap.Size(-123, -215) });
                    label.setStyle({                                        //给label设置样式，任意的CSS都是可以的
                        //fontSize:"14px",                                  //字号
                        border: "0",                                        //边
                        //textAlign:"center",                               //文字水平居中显示
                        //lineHeight:"120px",                               //行高，文字垂直居中显示
                        //background: "transparent",
                        background: "transparent",
                        //background:"url(images/tip_bg.png) no-repeat",    //背景图片！
                        cursor: "pointer"
                    });
                    addMarker(index, points, cov);
                    $.each(points, function (i, item) {
                        allpoints.push(item);                               //将一个车辆下所有的传感器经纬度信息存入全局变量allpoints中 
                    });
           
            }           
        },
        complete: function (x) {
            getCarDeviceCount++;                                         //每次根据车牌号获取实时数据的过程，都加1，用于判断所有车辆的实时数据是否取完
        }
    });
}
//在轨迹点上创建图标，并添加点击事件
function addMarker(index, points, explain) {
    var myIcon = new BMap.Icon("../../Plat/Monitor/img/car.png", new BMap.Size(50, 40));
    // 创建标注对象并添加到地图   
    for (var i = 0, pointsLen = points.length; i < pointsLen; i++) {
        var point = new BMap.Point(points[i].lng, points[i].lat);
        var marker = new BMap.Marker(point, { icon: myIcon });
        //为marker添加id属性
        marker.id = index;
        map.addOverlay(marker);
        //marker.setLabel(label);
        addClickHandler(marker, explain, point);
        //CloseWindow(marker);
    }
}

//信息框的样式
var opts = {
    width: 400,     // 信息窗口宽度
    height: 170,     // 信息窗口高度
};
//鼠标移动到标注时触发的事件(打开信息窗)
function addClickHandler(marker, explain, point) {
    marker.addEventListener("click", function (e) {
        openInfo(explain, point)
        //var arrayOverlays = map.getOverlays();
        //点击某个仓库时，应取消所有覆盖物的动画效果
        //for (var i = 0; i < arrayOverlays.length; i++) {
        //    arrayOverlays[i].setAnimation();
        //}
    });
}
//显示信息框
function openInfo(explain, point) {
    var infoWindow = new BMap.InfoWindow(explain, opts);  // 创建信息窗口对象 
    map.openInfoWindow(infoWindow, point); //开启信息窗口
}
//鼠标离开标注时触发的事件(关闭信息窗)
function CloseWindow(marker) {
    marker.addEventListener("mouseout", function (e) {
        map.closeInfoWindow();
    });
}

//根据原始数据计算中心坐标和缩放级别，并为地图设置中心坐标和缩放级别
function setZoom() {
    //根据所有点的经纬度确定地图中心点和级别，以确定视野范围
    mapview = map.getViewport(eval(allpoints));
    mapZoom = mapview.zoom;
    var centerPoint = mapview.center;
    map.centerAndZoom(centerPoint, mapZoom);

    //获取所有点的最大最小经纬度，即东北角、西南角两个点的经纬度
    var maxLng, minLng, maxLat, minLat, pointsres;
    if (allpoints.length > 0) {
        maxLng = allpoints[0].lng;
        minLng = allpoints[0].lng;
        maxLat = allpoints[0].lat;
        minLat = allpoints[0].lat;
        for (var i = allpoints.length - 1; i >= 0; i--) {
            pointsres = allpoints[i];
            if (pointsres.lng > maxLng) maxLng = pointsres.lng;
            if (pointsres.lng < minLng) minLng = pointsres.lng;
            if (pointsres.lat > maxLat) maxLat = pointsres.lat;
            if (pointsres.lat < minLat) minLat = pointsres.lat;
        };
        //将地图显示范围设定在指定区域，地图拖出该区域后会重新弹回
        var pointA = new BMap.Point(maxLng, maxLat);
        var pointB = new BMap.Point(minLng, minLat);
        var mapbounds = new BMap.Bounds(new BMap.Point(maxLng, maxLat), new BMap.Point(minLng, minLat));
    }
}

//点击车牌号，定位车辆
function showCar(index) {
    var d = selectpoints[index];
    if (typeof (d) == "undefined") {
        //关闭信息框并重新定位视野
        map.closeInfoWindow();
        setZoom();
        alert("未查询到此车辆的实时数据！");
    }
    else {
        map.centerAndZoom(selectpoints[index], mapZoom);
        var coverinfo = $("#covarr" + index).html();
        //显示所点击的车辆的详细信息
        openInfo(coverinfo, selectpoints[index]);
        //获取所有覆盖物
        //var arrayOverlays = map.getOverlays();
        //for (var i = 0; i < arrayOverlays.length; i++) {
        //    //先取消所有覆盖物的动画效果
        //    arrayOverlays[i].setAnimation();
        //    if (arrayOverlays[i].id == index) {
        //        console.log("覆盖物id:" + arrayOverlays[i].id);
        //        arrayOverlays[i].setAnimation(BMAP_ANIMATION_BOUNCE);            //动画效果是BMAP_ANIMATION_BOUNCE,坠落效果是BMAP_ANIMATION_DROP
        //    }
        //}
    }

}

function showOrder(taskId, carNumber) {
    var pageUrl = "/Plat/Grid/GridView?GridCode=Grid201809260956170063&taskId=" + taskId + "&carNumber=" + carNumber;
    top.OpenNewModel(pageUrl, "订单信息", 600, 400);
}

//参数：SN 开始时间  结束时间
function showHistoryPath(carNumber,snSensor,leavetime,startAddress,endAddress) {
    leavetime = leavetime.replace(new RegExp("/", "g"), "-");
    var CurrentTime = getFormatDate();
    var pageUrl = "/Plat/CarMonitor/CarHistoryPath?carNumber=" + carNumber + "&snSensor=" + snSensor + "&leavetime=" + leavetime + "&timenow=" + CurrentTime + "&startAddress=" + startAddress+ "&endAddress=" + endAddress;
    top.OpenNewModel(pageUrl, "历史轨迹", 800, 600);
}

function hideInfo() {
    map.closeInfoWindow();
}


function getFormatDate() {
    var nowDate = new Date();
    var year = nowDate.getFullYear();
    var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
    var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
    var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}


